import API from '../../utils/api'
import common from '../../utils/common'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    studentList: [],
    active: 0,
    ticketList: [],
    num: 1,
    isShowMask: false,
    isShowPayBox: false,
    bottom: '-100%',
    bottom2: '-100%',
    isShowBox: false,
    detailList:{},
    startTime:'',
    endTime:'',
    description:[],
    masterInfo:{},
    price:0,
    totalPrice:0,
    real_count:0,
    real_name:'',
    user_phone:'',
    studentListFive:[],
    isShowProtect:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      mer_id:options.id
    })
    this.getAcivityDetailData(options.id)
    this.getAllTickts(options.id)

  },
  // 我知道了
  alread () {
    this.setData({
      isShowProtect:false
    })
  },
  showAlert () {
    this.setData({
      isShowProtect:true
    })
  },
    // 获取票种列表
    getAllTickts(id) {
      var data = {
        productid: id
      }
      API.getAllTickts(data).then(res => {
        if (res.code == 0) {
          this.setData({
            ticketList: res.data,
            price: res.data[0].price,
            totalPrice:res.data[0].price,
            real_count:res.data[0].real_count,
            ticktsid:res.data[0].id
          })
        }
        console.log(res)
      })
    },
    toMore () {
      wx.navigateTo({
        url:'/pages/apply/apply?list='+ JSON.stringify(this.data.studentList)
      })
    },
    // 获取详情页数据
  getAcivityDetailData (id) {
    var data = {
      id:id
    }
    API.toActivityDetail(data).then(res=>{
      if(res.code==0) {
        var startTime = common.dateFormat(res.data.actInfo[0].startime)
        var endTime = common.dateFormat(res.data.actInfo[0].endtime)
        var description = JSON.parse(res.data.actInfo[0].description)
        console.log(res.data.partInfo.slice(0,5))
        this.setData({
          detailList:res.data.actInfo[0],
          startTime:startTime,
          endTime:endTime,
          description:description,
          masterInfo:res.data.masterInfo,
          studentList: res.data.partInfo,
          studentListFive:res.data.partInfo.slice(0,5)
        })
      }
    })
  },
  // 去发布活动页面
  toPublishPage() {
    wx.switchTab({
      url: '/pages/haveFun/haveFun',
    })
  },
  // 选择票种弹框
  selectTicketAlert() {
    this.setData({
      isShowMask: true,
      isShowBox: true
    })
    setTimeout(() => {
      this.setData({
        bottom: 0
      })
    }, 10)
  },
  closeMask() {
    this.setData({
      isShowMask: false,
      bottom: '-100%'
    })
    setTimeout(() => {
      this.setData({
        isShowBox: false
      })
    }, 10)
  },
  // 选择票种
  selectTicket(e) {
    var dataset = e.currentTarget.dataset
    var index = dataset.index
    var price = dataset.price
    var count = dataset.count-this.data.num
    var ticktsid = dataset.ticktsid
    console.log(price)
    var totalPrice = (this.data.num * price).toFixed(2)
    this.setData({
      active: index,
      price:price,
      totalPrice:totalPrice,
      real_count:count,
      ticktsid:ticktsid
    })
  },
  user (e) {
    this.setData({
      real_name:e.detail.value
    })
  },
  mobile (e) {
    this.setData({
      user_phone:e.detail.value
    })
  },
  // 减
  sumBtn() {
    if (this.data.num == 1) {
      return;
    }
    var numResult = this.data.num -= 1
    var count = this.data.real_count+=1
    var totalPrice = (Number(this.data.price )* numResult).toFixed(2)
    this.setData({
      num: numResult,
      totalPrice:totalPrice
      // real_count:count
    })
  },
  // 加
  addBtn() {
    // if (this.data.real_count< 2) {
    //   this.setData({
    //     real_count: 0
    //   })
    //   return
    // }
    var numResult = this.data.num += 1
    var totalPrice = (Number(this.data.price )* numResult).toFixed(2)
    var count = this.data.real_count-=1
  
    this.setData({
      num: numResult,
      totalPrice:totalPrice
      // real_count:count
    })
  },
  // 下一步
  nextBtn() {
    this.setData({
      isShowBox: false,
      isShowPayBox: true,
      bottom: '-100%'

    })
    setTimeout(() => {
      this.setData({

        bottom2: '0%'
      })
    }, 10)
  },
  // 去查看地图
  toMap (e) {
    var that = this
    console.log(that.data.detailList.latitude)
    var lat = Number(that.data.detailList.latitude)
    var lng = Number(that.data.detailList.longitude)
    var address = that.data.detailList.address
    wx.openLocation({
      latitude:lat,
      longitude:lng,
      scale: 13,
      name:address
    })
  },
  // 去他的主页
  toHimPage (e) {
    var uid = e.currentTarget.dataset.uid
    wx.navigateTo({
      url: '/pages/hisHomePage/hisHomePage?uid='+ uid
    })
  },
    // 关注
    attentionBtn (e){
      var uid = e.currentTarget.dataset.uid
      API.addCancer({masterid:uid}).then(res=>{
        if (res.code == 0) {
          wx.showToast({
            title: '关注成功',
            icon: 'success',
            duration: 2000
          })
          this.setData({
            attention:'已关注'
          })
          this.getAcivityDetailData(this.data.mer_id)
        }
      })
    },
      // 取消关注
  quxiaoCancer (e) {
    var uid = e.currentTarget.dataset.uid
    API.quxiaoCancer({masterid:uid}).then(res=>{
      if (res.code == 0) {
        wx.showToast({
          title: '取消成功',
          icon: 'success',
          duration: 2000
        })
        this.setData({
          attention:'关注'
        })
        this.getAcivityDetailData(this.data.mer_id)
      }
    })
  },
  // 关闭支付遮罩
  closePayMask() {
    this.setData({
      isShowMask: false,
      isShowPayBox: false,
      bottom: '-100%'
    })
  },
  // 返回上一页
  backPrevBtn() {
    this.setData({

      isShowPayBox: false,
      bottom2: '-100%',
      isShowBox: true

    })
    setTimeout(() => {
      this.setData({
        bottom: '0%',

      })
    }, 10)
  },
  // 去支付
  toPay() {
    // 支付成功后跳到个人中心
    var mobileRegex = /^1[2|3|4|5|6|7|8|9]\d{9}$/
    if (this.data.real_name=='') {
      wx.showModal({
        title: '',
        content: '请输入您的姓名',
      })
      return
    }
    else if (!mobileRegex.test(this.data.user_phone)) {
      wx.showModal({
        title: '',
        content: '请输入正确的手机号',
      })
      return
    } else {
      var data = {
        mer_id: this.data.mer_id,
        ticktsid: this.data.ticktsid,
        tickts_num: this.data.num,
        user_phone: this.data.user_phone,
        real_name: this.data.real_name

      }
      API.submitOrder(data).then(res=>{
        console.log(res)
        if (res.code == 0) {
            var orderId = res.data.order_id
            API.toPay({orderid:orderId}).then(payres=>{
              if (payres.code == 0) {
                wx.requestPayment({
                  timeStamp: payres.data.timeStamp,
                  nonceStr: payres.data.nonceStr,
                  package: payres.data.package,
                  signType: 'MD5',
                  paySign: payres.data.paySign,
                  success(result) {
                    console.log(result)
                    console.log('支付成功')
                    wx.showToast({
                      title: '支付成功',
                      icon: 'success',
                      duration: 2000
                    })
                    setTimeout(res=>{
                      wx.switchTab({
                        url: '/pages/memberCenter/memberCenter'
                      })
                    },2000)
                   
                   },
                  fail(result) { 
                    console.log(result)
                    console.log('支付失败')
                    wx.showToast({
                      title: '支付失败，请重新支付',
                      icon: 'success',
                      duration: 2000
                    })
                  }
                })
              }
             
            }).catch(fail=>{
              console.log(fail)
              console.log('失败了')
          
            })
        } else if(res.code == 1) {
          console.log('免费')
          // 免费票接口
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(res=>{
            wx.switchTab({
              url: '/pages/memberCenter/memberCenter'
            })
          },2000)
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  backHome () {
    wx.switchTab({
      url:'/pages/index/index'
    })
  },
  // 拨打电话
  concatHim () {
    var phone = this.data.detailList.phone
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      console.log("来自页面内转发按钮");
      console.log(res.target);
    }
    else {
      console.log("来自右上角转发菜单")
    }
    API.share({productid:this.data.mer_id}).then(response=>{
      if (response.code == 0) {
        console.log('转发成功')
      }
    })
    return {
      title: this.data.detailList.store_name,
      path: '/pages/activityDetail/activityDetail?id='+this.data.mer_id,
      imageUrl: "",
      success: function(res){
        console.log("转发成功2222", res);
        API.share({productid:this.data.mer_id}).then(response=>{
          if (response.code == 0) {
            console.log('转发成功')
          }
        })
      },
      fail: (res) => {
        console.log("转发失败", res);
      }

  }
}
})